package shells

import (
	"bufio"
	"fmt"
	"github.com/fatih/color"
	"github.com/ihaiker/tfwrapper/internal/errors"
	"github.com/ihaiker/tfwrapper/internal/util"
	"github.com/sirupsen/logrus"
	"io"
	"os"
	"strings"
)

//PromptUserForInput Prompt the user for text in the CLI. Returns the text entered by the user.
func PromptUserForInput(prompt string, writer io.Writer) (string, error) {
	n, err := writer.Write([]byte(prompt))
	if err != nil {
		logrus.Error(err)
		return "", errors.WithStackTrace(err)
	}
	if n != len(prompt) {
		logrus.Errorln("Failed to write data")
		return "", errors.WithStackTrace(err)
	}
	reader := bufio.NewReader(os.Stdin)
	text, err := reader.ReadString('\n')
	if err != nil {
		return "", errors.WithStackTrace(err)
	}
	return strings.TrimSpace(text), nil
}

//PromptUserForYesNo Prompt the user for a yes/no response and return true if they entered yes.
func PromptUserForYesNo(nonInteractive *bool, prompt string, writer io.Writer) error {
	if util.Bool(nonInteractive) {
		_, _ = fmt.Fprintf(os.Stderr, "%s (yes/no): yes\n", prompt)
		_, _ = fmt.Fprintln(os.Stderr, "The non-interactive flag is set to true, so assuming 'yes' for all prompts")
		return nil
	}

	resp, err := PromptUserForInput(fmt.Sprintf("%s (yes/no) ", prompt), writer)
	if err != nil {
		return errors.WithStackTrace(err)
	}

	switch strings.ToLower(resp) {
	case "y", "yes":
		return nil
	default:
		return errors.New(color.HiRedString("unconfirmed"))
	}
}
